//
//  SearchViewController.m
//  GiftSay
//
//  Created by QQn1993 on 16/1/8.
//  Copyright © 2016年 liyinkai. All rights reserved.
//

#import "SearchViewController.h"

@interface SearchViewController ()<UITextFieldDelegate,UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,UITableViewDataSource,UITableViewDelegate>

@property (nonatomic,strong) UISearchBar *searchbar;
@property (nonatomic,strong) UITableView *table;
@property (nonatomic,strong) UICollectionView *collection;

//判断搜索是否正在输入
@property (nonatomic,assign) NSInteger isEding;

//加载
@property (nonatomic,assign) NSInteger number;

//滑动的线
@property (nonatomic,strong) UILabel *line;
@property (nonatomic,strong) UILabel *volatileline;
//切换按钮
@property (nonatomic,strong) UIButton *items;
@property (nonatomic,strong) UIButton *post;

@property (nonatomic,strong) NSMutableArray *ItemsArray;
@property (nonatomic,strong) NSMutableArray *PostArray;

@end

@implementation SearchViewController

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.ItemsArray = [NSMutableArray arrayWithCapacity:0];
    self.PostArray = [NSMutableArray arrayWithCapacity:0];
    self.number = 0;
    
    self.searchbar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, kWidth, kHeight)];
    self.searchbar.placeholder = @"快选一份礼物，送给亲爱的Ta吧";
    self.searchbar.delegate = self;
    self.searchbar.clearsContextBeforeDrawing = YES;
    
    self.navigationItem.titleView = self.searchbar;
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(dismiss)];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeDatasource) name:UITextFieldTextDidChangeNotification object:nil];
    
    self.isEding = 0;
    
    [self createdChangeButton];
    
    [self createdTableview];
    [self createdCollectionview];
    
    // Do any additional setup after loading the view.
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

- (void)changeDatasource
{
    NSLog(@"%@",self.searchbar.text);
    self.isEding = 1;
    
    if (self.searchbar.text.length == 0 || self.searchbar.text == nil) {
        
        NSLog(@"kong");
        
        self.line.hidden = YES;
        self.items.hidden = YES;
        self.post.hidden = YES;
        self.volatileline.hidden = YES;
        self.collection.hidden = YES;
        self.table.hidden = YES;
    }
    else{
        self.line.hidden = NO;
        self.items.hidden = NO;
        self.post.hidden = NO;
        self.volatileline.hidden = NO;
        self.collection.hidden = NO;
        self.table.hidden = NO;
        
        [self reload];
    }
}

#pragma mark 刷新
- (void)reload
{
    NSLog(@"刷新");
    if (self.ItemsArray.count > 0) {
        [self.ItemsArray removeAllObjects];
    }
    
    if (self.PostArray.count > 0) {
        [self.PostArray removeAllObjects];
    }
    
    [self getItemsAndPost];
}

#pragma mark 加载
- (void)addItem
{
    NSLog(@"加载");
    
    self.number += 1;
    [self getItemsAndPost];
}



//创建切换button
- (void)createdChangeButton
{
    self.line = [[UILabel alloc] initWithFrame:CGRectMake(0, kHeight / 15, kWidth / 2, kHeight / 300)];
    self.line.backgroundColor = [UIColor redColor];
    self.line.hidden = YES;
    [self.view addSubview:self.line];
    
    self.items = [UIButton buttonWithType:UIButtonTypeCustom];
    self.items.hidden = YES;
    self.items.frame = CGRectMake(0,0, kWidth / 2, kHeight / 15);
//    items.backgroundColor = [UIColor redColor];
    self.items.backgroundColor = [UIColor whiteColor];
    [self.items setTitle:@"礼物" forState:UIControlStateNormal];
    [self.items setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    self.items.titleLabel.textAlignment = NSTextAlignmentCenter;
    [self.items addTarget:self action:@selector(bringColletionviewToFont) forControlEvents:UIControlEventTouchUpInside];
    
    self.post = [UIButton buttonWithType:UIButtonTypeCustom];
    self.post.hidden = YES;
    self.post.frame = CGRectMake(kWidth / 2, 0, kWidth / 2,kHeight / 15);
    [self.post setTitle:@"攻略" forState:UIControlStateNormal];
    self.post.backgroundColor = [UIColor whiteColor];
    [self.post setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    self.post.titleLabel.textAlignment = NSTextAlignmentCenter;
    [self.post addTarget:self action:@selector(bringTableviewTofont) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:self.items];
    [self.view addSubview:self.post];
    
    self.volatileline = [[UILabel alloc] initWithFrame:CGRectMake(kWidth / 2 - kHeight / 1200, 0, kHeight / 600, kHeight / 15)];
    self.volatileline.backgroundColor = [UIColor lightGrayColor];
    self.volatileline.hidden = YES;
    [self.view addSubview:self.volatileline];
    
}

- (void)bringColletionviewToFont
{
    [UIView animateWithDuration:0.5 animations:^{
        self.line.frame = CGRectMake(0, kHeight / 15, kWidth / 2, kHeight / 300);
    }];
    
    [self.view bringSubviewToFront:self.collection];
}

- (void)bringTableviewTofont
{
    [UIView animateWithDuration:0.5 animations:^{
        self.line.frame = CGRectMake(kWidth / 2, kHeight / 15, kWidth / 2, kHeight / 300);
    }];
    
    [self.view bringSubviewToFront:self.table];
    
}

//创建collectionview
- (void)createdCollectionview
{
    UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc] init];
    flow.sectionInset = UIEdgeInsetsMake(kWidth / 50, kWidth / 50, kWidth/50, kWidth/50);
    
    flow.minimumInteritemSpacing = kWidth / 50;
    flow.minimumLineSpacing = kWidth / 50;
    
    self.collection = [[UICollectionView alloc] initWithFrame:CGRectMake(0, self.line.frame.origin.y + kHeight / 150, self.view.size.width, self.view.size.height - 64 - self.line.frame.origin.y + kHeight / 150) collectionViewLayout:flow];
    self.collection.backgroundColor = [UIColor colorWithWhite:0.9 alpha:1];
    
    [self.collection registerClass:[BaseCollectionViewCell class] forCellWithReuseIdentifier:@"BaseCollectionViewCell"];
    
    self.collection.delegate = self;
    self.collection.dataSource = self;
    self.collection.hidden = YES;
    
    [self.view addSubview:self.collection];
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(kWidth / 50 * 23, kHeight / 10 * 4);
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return  self.ItemsArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    BaseCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"BaseCollectionViewCell" forIndexPath:indexPath];
    if (self.ItemsArray.count > indexPath.row) {
        cell.item = self.ItemsArray[indexPath.row];
    }
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    Items *item = self.ItemsArray[indexPath.row];
    
    WebViewController *web = [[WebViewController alloc] init];
    web.url = [NSString stringWithFormat:@"%@%@",kItemsInfo,item.ID];
    
    [self.navigationController pushViewController:web animated:YES];
    
}

#pragma mark 创建tableview
- (void)createdTableview
{
    self.table = [[UITableView alloc] initWithFrame:CGRectMake(0, self.line.frame.origin.y + kHeight / 150, kWidth, kHeight - 64 - self.line.frame.origin.y - kHeight/150) style:UITableViewStyleGrouped];
//    self.table.backgroundColor = [UIColor cyanColor];
    
    [self.table registerClass:[UITableViewCell class] forCellReuseIdentifier:@"UITableViewCell"];
    
    self.table.dataSource = self;
    self.table.delegate = self;
    self.table.hidden = YES;
    
    [self.view addSubview:self.table];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.PostArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
//    NSLog(@"%f",kHeight / 4);
    return kHeight / 4;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell"];
    
//    NSLog(@"%ld",indexPath.row);
    NSDictionary *dic = [NSDictionary dictionaryWithDictionary:self.PostArray[indexPath.row]];
//    cell.backgroundColor = [UIColor redColor];
    cell.textLabel.text = dic[@"name"];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dic = [NSDictionary dictionaryWithDictionary:self.PostArray[indexPath.row]];
    WebViewController *web = [[WebViewController alloc] init];
    //可拼接的web
//    web.url = [NSString stringWithFormat:@"%@%@",kPostInfo,dic[@"id"]];
//    web.type = @"html";
    
    web.url = [NSString stringWithFormat:@"%@%@",kPostInfoTow,dic[@"id"]];
    
    [self.navigationController pushViewController:web animated:YES];
}

#pragma mark 获取数据
- (void)getItemsAndPost
{
    //获取collection数据
    
    NSString *getEndUrl = [kSearchGETEndURL stringByReplacingOccurrencesOfString: [NSString stringWithFormat:@"offset=%ld",(self.number * 20)] withString:@"offset=0"];
    
    NSString *keyWord = [NSString stringWithString:[self.searchbar.text stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet symbolCharacterSet]]];
    
    NSString *urlcollection = [NSString stringWithFormat:@"%@%@%@",kSearchGetItemsBeginURL,keyWord,getEndUrl];
    
    NSString *urltable = [NSString stringWithFormat:@"%@%@%@",kSearchGetPostBeginURL,keyWord,getEndUrl];
    
#pragma mark 获取collection items
    [LYKNetWorkTool getWithUrl:urlcollection parameter:nil httpHeader:nil resposeType:ResponseTypeDATA success:^(id result) {
       
        id any = [NSJSONSerialization JSONObjectWithData:result options:0 error:nil];
//        NSLog(@"************%@",any);
        
        NSDictionary *data = any[@"data"];
        NSArray *items = [NSArray arrayWithArray:data[@"items"]];
        for (NSDictionary *datasource in items) {
            
//            NSDictionary *dic = datasource[@"data"];
            Items *item = [[Items alloc] init];
            item.like = [NSString stringWithFormat:@"%@",datasource[@"favorites_count"]];
            item.ID = [NSString stringWithFormat:@"%@",datasource[@"id"]];
            item.cover_icon = datasource[@"cover_image_url"];
            item.title = datasource[@"name"];
            item.price = [NSString stringWithFormat:@"%@",datasource[@"price"]];
            
            [self.ItemsArray addObject:item];
        }
        
        NSLog(@"****%ld",self.ItemsArray.count);
        [self.collection reloadData];
        
    } fail:^(NSError *erro) {
        NSLog(@"%@",erro);
    }];
    
#pragma mark 获取table数据
    [LYKNetWorkTool getWithUrl:urltable parameter:nil httpHeader:nil resposeType:ResponseTypeDATA success:^(id result) {
        
        id any = [NSJSONSerialization JSONObjectWithData:result options:0 error:nil];
//        NSLog(@"%@",any);
        NSDictionary *data = any[@"data"];
        NSArray *post = [NSArray arrayWithArray:data[@"posts"]];
//        NSLog(@"%ld****",post.count);
        
        for (NSDictionary *dic in post) {
            [self.PostArray addObject:dic];
        }
        
        [self.table reloadData];
        
    } fail:^(NSError *erro) {
        
    }];
    
}

//取消方法
- (void)dismiss
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
